package com.java.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.common.utils.R;
import com.java.gulimall.product.service.CategoryBrandRelationService;
import com.java.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;

import com.java.gulimall.product.dao.CategoryDao;
import com.java.gulimall.product.entity.CategoryEntity;
import com.java.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;

    @Override
    public List<CategoryEntity> tree() {
        List<CategoryEntity> all = this.baseMapper.selectList(null);
        // 查询一级菜单
        List<CategoryEntity> level1Menus = all.stream().filter(e -> e.getParentCid() == 0)
                .map(e -> {
                    // 组装子菜单
                    e.setChildren(fetchChildren(e, all));
                    return e;
                })
                .sorted((e1, e2) -> (e1.getSort() == null ? 0 : e1.getSort()) - (e2.getSort() == null ? 0 : e2.getSort()))
                .collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public R removeMenuByIds(List<Long> catIds) {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().in(CategoryEntity::getParentCid, catIds));
        if (!CollectionUtils.isEmpty(categoryEntities)) {
            return R.error("禁止删除有子节点的分类!");
        }
        this.baseMapper.deleteBatchIds(catIds);
        return R.ok();
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        getParentPath(catelogId, paths);
        // 翻转
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * 缓存失效模式 删除多个缓存
     */
    @CacheEvict(value = {"category"}, allEntries = true)
//    @Caching(evict = {@CacheEvict(value = {"category"}, key = "'level1Categories'"),@CacheEvict(value = {"category"}, key = "'CatelogJson'")})
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    // 代表当前方法的返回值需要缓存,如果缓存中有,方法不用调用.
    @Cacheable(value = {"category"}, key = "'level1Categories'")
    public List<CategoryEntity> getLevel1Categorys() {
        return this.baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, 0));
    }

    /**
     * 产生堆外内存溢出: OutOfDirectMemoryError
     * springboot2.0以后默认使用lettuce作为操作redis的客户端的,它使用netty进行通信
     * lettuce的bug导致netty堆外内存溢出 -Xmx300m. netty如果没有指定堆外内存,默认使用-Xmx300m
     * 可以通过-Dio.netty.maxDirectMemory进行设置
     * 解决方案:不能使用-Dio.netty.maxDirectMemory只去调大堆外内存
     * 1)升级lettuce客户端 2)切换使用jedis
     */
    public Map<String, List<Catelog2Vo>> getCatelogJson2() {
        /**
         * 缓存三大问题
         * 1.空结果缓存:解决缓存穿透
         * 2.设置过期时间加随机值:解决缓存雪崩
         * 3.加锁:解决缓存击穿
         */
        String categoryJson = redisTemplate.opsForValue().get("categoryJson");
        if (StringUtils.isEmpty(categoryJson)) {
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonWithRedissonLock();
            String s = JSON.toJSONString(catelogJsonFromDb);
            redisTemplate.opsForValue().set("categoryJson", s);
        }
        return JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
    }

    @Override
    @Cacheable(value = {"category"},key = "'CatelogJson'")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        /**
         * 缓存三大问题
         * 1.空结果缓存:解决缓存穿透
         * 2.设置过期时间加随机值:解决缓存雪崩
         * 3.加锁:解决缓存击穿
         */
            return getCatelogJsonWithRedissonLock();
    }

    private Map<String, List<Catelog2Vo>> getCatelogJsonWithRedissonLock() {
        RLock lock = redisson.getLock("category-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            // 查询数据库
            dataFromDb = getDataFromDb();
        } finally {
            // 释放锁
            lock.unlock();
        }
        return dataFromDb;

    }

    private Map<String, List<Catelog2Vo>> getCatelogJsonWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        // 加锁,设置过期时间,保证原子性
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            // 加锁成功
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                // 查询数据库
                dataFromDb = getDataFromDb();
            } finally {
                // 释放锁,redis+lua脚本保证原子性
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Long flag = this.redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            // 加锁失败,重试
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonWithRedisLock();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String categoryJson = redisTemplate.opsForValue().get("categoryJson");
        if (!StringUtils.isEmpty(categoryJson)) {
            return JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }

        // 查询所有分类
        List<CategoryEntity> all = this.baseMapper.selectList(null);

        // 查询1级分类
        List<CategoryEntity> level1Categorys = getCategoriesByPid(all, 0L);
        // 组装数据
        Map<String, List<Catelog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查询2级分类
            List<CategoryEntity> categoryEntities = getCategoriesByPid(all, v.getCatId());

            List<Catelog2Vo> catelog2Vos = categoryEntities.stream().map(l2 -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo();
                catelog2Vo.setCatalogId(v.getCatId().toString());
                catelog2Vo.setId(l2.getCatId().toString());
                catelog2Vo.setName(l2.getName());

                // 查询3级分类
                List<CategoryEntity> categoryEntityList3 = getCategoriesByPid(all, l2.getCatId());
                List<Catelog2Vo.Catelog3Vo> catelog3VoList = categoryEntityList3.stream().map(l3 -> {
                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                    catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                    catelog3Vo.setId(l3.getCatId().toString());
                    catelog3Vo.setName(l3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(catelog3VoList);

                return catelog2Vo;
            }).collect(Collectors.toList());

            return catelog2Vos;
        }));

        return collect;
    }

    private Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {
        // 查询所有分类
        List<CategoryEntity> all = this.baseMapper.selectList(null);

        // 查询1级分类
        List<CategoryEntity> level1Categorys = getCategoriesByPid(all, 0L);
        // 组装数据
        Map<String, List<Catelog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查询2级分类
            List<CategoryEntity> categoryEntities = getCategoriesByPid(all, v.getCatId());

            List<Catelog2Vo> catelog2Vos = categoryEntities.stream().map(l2 -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo();
                catelog2Vo.setCatalogId(v.getCatId().toString());
                catelog2Vo.setId(l2.getCatId().toString());
                catelog2Vo.setName(l2.getName());

                // 查询3级分类
                List<CategoryEntity> categoryEntityList3 = getCategoriesByPid(all, l2.getCatId());
                List<Catelog2Vo.Catelog3Vo> catelog3VoList = categoryEntityList3.stream().map(l3 -> {
                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                    catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                    catelog3Vo.setId(l3.getCatId().toString());
                    catelog3Vo.setName(l3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(catelog3VoList);

                return catelog2Vo;
            }).collect(Collectors.toList());

            return catelog2Vos;
        }));

        return collect;
    }

    private List<CategoryEntity> getCategoriesByPid(List<CategoryEntity> all, Long parentCid) {
        return all.stream().filter(e -> e.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    private List<Long> getParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            getParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 组装子菜单
     *
     * @param current 当前对象
     * @param all     所有对象集合
     * @return
     */
    private List<CategoryEntity> fetchChildren(CategoryEntity current, List<CategoryEntity> all) {
        // 查询当前对象的子对象
        List<CategoryEntity> children = all.stream().filter(e -> e.getParentCid().equals(current.getCatId()))
                // 递归,设置子对象集合
                .peek(e -> e.setChildren(fetchChildren(e, all)))
                // 排序
                .sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort())))
                .collect(Collectors.toList());
        return children;
    }

}